# backend/utils/api_client.py
import httpx
from .config import settings


async def fetch_book_info(isbn: str):
    # 尝试豆瓣API
    try:
        async with httpx.AsyncClient() as client:
            response = await client.get(
                f"https://api.douban.com/v2/book/isbn/{isbn}",
                params={"apikey": settings.DOUBAN_API_KEY}
            )
            if response.status_code == 200:
                data = response.json()
                return {
                    "title": data.get("title"),
                    "author": ", ".join(data.get("author", [])),
                    "cover_url": data.get("image")
                }
    except Exception:
        pass

    # 尝试国家图书馆API
    try:
        async with httpx.AsyncClient() as client:
            response = await client.get(
                f"https://api.nlc.cn/book?isbn={isbn}",
                headers={"Authorization": f"Bearer {settings.NLC_API_KEY}"}
            )
            if response.status_code == 200:
                data = response.json()
                if data.get("books"):
                    book = data["books"][0]
                    return {
                        "title": book.get("title"),
                        "author": book.get("author"),
                        "cover_url": book.get("cover_url")
                    }
    except Exception:
        pass

    return None
